package com.xique.door.command.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.AccessDevice;
import com.xique.door.bean.domain.CardDevice;
import com.xique.door.bean.domain.DCard;
import com.xique.door.bean.domain.User;
import com.xique.door.bean.domain.estate.EstateUser;
import com.xique.door.bean.dto.EstateUserDownDTO;
import com.xique.door.command.IDeviceEstateUserCommandService;
import com.xique.door.constant.AccessCommandConstant;
import com.xique.door.device.command.AccessCommandHQService;
import com.xique.door.device.freeview.constant.CommandStatus;
import com.xique.door.device.freeview.service.biz.FreeviewCommandBizService;
import com.xique.door.device.hq.bean.dto.HQResultDTO;
import com.xique.door.device.hq.bean.dto.HQResultDataDTO;
import org.apache.commons.collections4.map.SingletonMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shd
 * @create 2022/6/9 18:45
 */
@Service
public class DeviceEstateUserCommandServiceImpl implements IDeviceEstateUserCommandService {

    @Autowired
    private AccessCommandHQService accessCommandHQService;

    @Autowired
    private FreeviewCommandBizService freeviewCommandBizService;

    @Override
    public AjaxResult getReturnHQ(HQResultDTO dto, String fromType) {
        if (0 != dto.getResult_code()) {
            return AjaxResult.error("下发失败");
        }
        List<String> successMsgList = new ArrayList<>();
        List<String> errorMsgList = new ArrayList<>();

        if (null != dto && null != dto.getData()) {
            for (HQResultDataDTO data : dto.getData()) {
                String message = "";
                if (!data.getStatus().equals(AccessCommandConstant.DeviceStatus.SUCCESS)) {
                    message = data.getDeviceCode() + ":" + data.getMsg() + (data.getResult() != null ? " 具体原因：" + data.getResult().getInfo().getDetail() : "") + "<br/>";
                    errorMsgList.add(message);
                } else {
                    message = data.getDeviceCode() + ":" + data.getMsg() + "<br/>";
                    successMsgList.add(message);
                }
            }
        }
        //TODO
        if (null != dto && null != dto.getData_obj()) {

        }
        String successMsg = StringUtils.join(successMsgList, "");
        String errorMsg = StringUtils.join(errorMsgList, "");
        StringBuilder returnMsg = new StringBuilder();
        if (StringUtils.isNotEmpty(errorMsg)) {
            returnMsg.append("失败下发设备如下：<br/>" + errorMsg + "<br/>");
        }
        if (StringUtils.isNotEmpty(successMsg)) {
            returnMsg.append("成功下发设备如下：<br/>" + successMsg);
        }
//        String returnMsg = "失败下发设备如下：<br/>" + errorMsg +  "<br/>成功下发设备如下：<br/>" + successMsg;
        if (AccessCommandConstant.FromType.APP.equals(fromType)) {
            StringUtils.replace(returnMsg.toString(), "<br/>", "\n");
        }
        if (!errorMsgList.isEmpty()) {
            return AjaxResult.success(returnMsg.toString());
        }
        return AjaxResult.success(returnMsg.toString());
    }

    @Override
    public AjaxResult downUsers(List<AccessDevice> devices, List<EstateUserDownDTO> users) {

        List<AccessDevice> hqAccessDevices = devices.stream().filter(e -> e.getModel().equals(AccessCommandConstant.DeviceType.HQ)).collect(Collectors.toList());
        List<AccessDevice> freeviewAccessDevices = devices.stream().filter(e -> Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_32, AccessCommandConstant.DeviceType.FREEVIEW_45).contains(e.getModel())).collect(Collectors.toList());

        List<EstateUserDownDTO> cardUsers = users.stream().filter(v -> StringUtils.isNotBlank(v.getCardSn())).collect(Collectors.toList());
        List<EstateUserDownDTO> faceUsers = users.stream().filter(v -> StringUtils.isNotBlank(v.getFaceUrl())).collect(Collectors.toList());

        if (!hqAccessDevices.isEmpty()) {
            Object o = accessCommandHQService.downBatchEstateUserAndCardInfos(hqAccessDevices, faceUsers, cardUsers);
            AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
            if (AjaxResult.isError(result)) {
                return result;
            }
        }
        if (!freeviewAccessDevices.isEmpty()) {
            if (CollectionUtil.isNotEmpty(faceUsers)) {
                Object o = freeviewCommandBizService.downEstateUserInfos(freeviewAccessDevices, faceUsers);
                AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
                if (AjaxResult.isError(result)) {
                    return result;
                }
            }
            if (CollectionUtil.isNotEmpty(cardUsers)) {
                Object o = freeviewCommandBizService.downEstateUserCardInfos(freeviewAccessDevices, cardUsers);
                AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
                if (AjaxResult.isError(result)) {
                    return result;
                }
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteUsers(List<AccessDevice> devices, List<EstateUserDownDTO> users) {
        List<AccessDevice> hqAccessDevices = devices.stream().filter(e -> e.getModel().equals(AccessCommandConstant.DeviceType.HQ)).collect(Collectors.toList());
        List<AccessDevice> freeviewAccessDevices = devices.stream().filter(e -> Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_32, AccessCommandConstant.DeviceType.FREEVIEW_45).contains(e.getModel())).collect(Collectors.toList());

        List<EstateUserDownDTO> cardUsers = users.stream().filter(v -> StringUtils.isNotBlank(v.getCardSn())).collect(Collectors.toList());
        List<EstateUserDownDTO> faceUsers = users.stream().filter(v -> StringUtils.isNotBlank(v.getFaceUrl())).collect(Collectors.toList());

        if (!hqAccessDevices.isEmpty()) {
            List<String> devSns = hqAccessDevices.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            List<String> customIds = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(faceUsers)) {
                customIds.addAll(faceUsers.stream().map(EstateUserDownDTO::getCustomId).distinct().collect(Collectors.toList()));
            }
            if (CollectionUtil.isNotEmpty(cardUsers)) {
                customIds.addAll(cardUsers.stream().map(EstateUserDownDTO::getCardCustomId).distinct().collect(Collectors.toList()));
            }

            Object o = accessCommandHQService.delBatchUserInfos(devSns, Collections.singletonMap("customId", customIds), AccessCommandConstant.VERSION);
            AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
            if (AjaxResult.isError(result)) {
                return result;
            }
        }
        if (!freeviewAccessDevices.isEmpty()) {
           List<String> devSns = freeviewAccessDevices.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(faceUsers)) {
                Object o = freeviewCommandBizService.deleteEstateUserInfos(devSns, faceUsers);
                AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
                if (AjaxResult.isError(result)) {
                    return result;
                }
            }
            if (CollectionUtil.isNotEmpty(cardUsers)) {
                Object o = freeviewCommandBizService.deleteEstateUserCardInfos(devSns, cardUsers);
                AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
                if (AjaxResult.isError(result)) {
                    return result;
                }
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteCard(DCard card, List<CardDevice> cardDevices) {
        List<CardDevice> hqCardDevice = cardDevices.stream().filter(item -> AccessCommandConstant.DeviceType.HQ.equals(item.getModel())).collect(Collectors.toList());
        List<CardDevice> freeviewCardDevice = cardDevices.stream().filter(item -> AccessCommandConstant.DeviceType.FREEVIEW_45.equals(item.getModel())|| AccessCommandConstant.DeviceType.FREEVIEW_32.equals(item.getModel())).collect(Collectors.toList());
        if (!hqCardDevice.isEmpty()) {
            //海清卡片删除
            List<String> devSns = cardDevices.stream().map(CardDevice::getDevSn).collect(Collectors.toList());
            Object o = accessCommandHQService.delUserInfos(devSns, new SingletonMap<>("customId", card.getCustomId()), AccessCommandConstant.VERSION);
        }

        if (!freeviewCardDevice.isEmpty()) {
            //全视通卡片下发
            List<String> devSns = freeviewCardDevice.stream().map(CardDevice::getDevSn).collect(Collectors.toList());
            freeviewCommandBizService.deleteCardInfo(devSns, card);
        }


        return AjaxResult.success();
    }

    @Override
    public AjaxResult downCard(List<AccessDevice> devices, List<EstateUserDownDTO> users) {
        List<AccessDevice> hqAccessDevices = devices.stream().filter(e -> e.getModel().equals(AccessCommandConstant.DeviceType.HQ)).collect(Collectors.toList());
        List<AccessDevice> freeviewAccessDevices = devices.stream().filter(e -> Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_32, AccessCommandConstant.DeviceType.FREEVIEW_45).contains(e.getModel())).collect(Collectors.toList());
        if (!hqAccessDevices.isEmpty()) {
            Object o = accessCommandHQService.downBatchEstateUserInfos(hqAccessDevices, users);
            AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
            if (AjaxResult.isError(result)) {
                return result;
            }
        }
        if (!freeviewAccessDevices.isEmpty()) {
            Object o = freeviewCommandBizService.downEstateUserCardInfos(freeviewAccessDevices, users);
            AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
            if (AjaxResult.isError(result)) {
                return result;
            }
        }
        return null;
    }
}
